package com.rinlink.jbcodec.creator;

import com.alibaba.fastjson.JSONObject;
import com.rinlink.jbcodec.common.CreatorUtils;
import com.rinlink.jbcodec.common.MapUtils;
import com.rinlink.jbcodec.exception.AttributePropertyException;
import com.rinlink.jbcodec.exception.FieldValueException;
import com.rinlink.jbcodec.transform.StringToBytes;
import com.rinlink.jbcodec.transform.Transform;

public class VariableStringToBytesCreator extends ObjectToBytesCreator<String> {

    @Override
    protected Transform<byte[]> create(String s, JSONObject attr, JSONObject source) {
        String charset = MapUtils.getOrDefault(attr,"charset","utf-8");
        int bytes = CreatorUtils.getBytes(attr,source);
        if (s.length() != bytes)
            throw new FieldValueException();

        return new StringToBytes(s,bytes,charset);
    }

}
